from datetime import datetime

from fastapi.responses import JSONResponse
from pydantic import Json
from app.api.admin import JWTException
from app.api.admin.model.system.user import UserModel
from app.api.admin.schema.system.user import UserInSchema, UserLoginSchema, UserOutSchema, UserSearchSchema

from app.exceptions import http_resp
from app.dependencies.database import db

from sqlalchemy import insert, select

from app.exceptions.exception import AppException
from app.modules.auth.manager import token_manager


class UserService():

    async def edit(self, **kwargs):
        # print("user service edit")
        user = UserModel()
        for key in kwargs.keys():
            if hasattr(user, key):
                setattr(user, key, kwargs[key])
        await db.execute(
            UserModel.__table__.insert().values(**kwargs)
        )
        print(UserModel.__table__)
        return

    async def create(self, user_in: UserInSchema):
        user = user_in.model_dump()
        print("user", user)
        result = await db.execute(insert(UserModel).values(**user))
        print("新增用户", result)
        return result

    async def get_list(self, params: UserSearchSchema):
        print("user service get list")
        where_params = [UserModel.is_deleted == 0]
        query = select(UserModel).where(*where_params)
        if 1 == 1:
            raise AppException(
                exc=http_resp.HttpResp.ASSERT_ARGUMENT_ERROR, msg="token过期")
        results = await db.fetch_all(query)
        # print("user service 取出 user_id", self.request.state.user_id)
        # print([type(result) for result in results])
        # print([UserOutSchema.model_validate(result) for result in results])

        return await db.fetch_all(query)

    async def get_all(self, params: UserSearchSchema):
        print("user service get one by params")
        return

    async def detail(self, params: UserSearchSchema):
        print("user service get one by params")
        return

    async def remove(self, user_id: int):
        pass

    async def login(self, user_login_in: UserLoginSchema):
        query = select(UserModel).where(
            UserModel.username == user_login_in.username)
        res = await db.fetch_one(query)
        user = UserOutSchema.model_validate(res)
        if not user:
            raise AppException(
                exc=http_resp.HttpResp.LOGIN_ACCOUNT_ERROR)
        if user.password != user_login_in.password:
            raise AppException(
                exc=http_resp.HttpResp.LOGIN_ACCOUNT_ERROR)
        return {
            "accessToken": "Bearer " + token_manager.create_token(identity=user.id)
        }

    @classmethod
    def instance(cls):
        '''实例化'''
        return cls()
